/**
 * ipcRenderer 渲染ipc操作
 *
 */
const { contextBridge, ipcRenderer } = require('electron');

const handleSend = async (evName, agr) => {
  return await ipcRenderer.invoke(evName, agr);
};

const copy = (text) => {
  return ipcRenderer.invoke('clipboard-copy', text);
};

const show = () => {
  return ipcRenderer.invoke('clipboard-show');
};

const capture = async () => {
  const sources = await ipcRenderer.invoke('capture-page', '');
  for (const source of sources) {
    if (source.name === '屏幕 1') {
      window.source = source;
      const str = source.thumbnail.crop({
        x: 0,
        y: 0,
        width: 900,
        height: 500,
      });
      const imgSrc = str.toDataURL();
      return imgSrc;
    }
  }
};

// sendUrl
const sendUrl = async (url) => {
  const res = await ipcRenderer.invoke('on-url-server', url);
  return res;
}

const sendOpenSellUrl = (url) => {
  ipcRenderer.invoke('on-open-shell', url);
}

const sendIPQueryRegion = async(ip) => {
  const res = await ipcRenderer.invoke('on-region-server', ip);
  return res;
}

const sendHoliday = async () => {
  return await ipcRenderer.invoke('on-server-holiday');
}

// 客户端调用，打开子窗口
const sendOpenView = (url) => {
  ipcRenderer.invoke('on-open-view', url);
}


// 预渲染，暴露一个myApi对象，到window身上。渲染进程页面，通过window.myApi 拿到需要的数据
contextBridge.exposeInMainWorld('myApi', {
  platform: process.platform,
  handleSend,
  copy,
  show,
  capture,
  sendUrl,
  sendOpenSellUrl,
  sendIPQueryRegion,
  sendHoliday,
  sendOpenView,
});
